package com.google.code.hibernate.rest.representation;

import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.hibernate.rest.MarshalException;
import com.google.code.hibernate.rest.UnmarshalException;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;

/**
 * 
 * @author wangzijian
 * 
 */
public abstract class AbstractXStreamPepresentor implements Representor {
	
	private static final ThreadLocal<String> BASE_URL = new ThreadLocal<String>();
	
	protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
	
	protected abstract XStream xStream();
	
	public static String getBaseURL() {
		return BASE_URL.get();
	}
	
	@Override
	public Object fromRepresentation(String string) throws UnmarshalException {
		if (string == null) {
			return null;
		}
		try {
			return xStream().fromXML(string);
		} catch (XStreamException e) {
			throw new UnmarshalException(e);
		}
	}

	@Override
	public String representEntity(Object entity, String baseURL) throws MarshalException {
		return marshal(entity, baseURL);
	}

	@Override
	public String representEntities(String entityName, List<?> entities, String baseURL) throws MarshalException {
		return marshal(EntityList.create(entityName, entities), baseURL);
	}
	
	@Override
	public String representEntityCategories(Set<String> entityCategories, String baseURL) throws MarshalException {
		return marshal(new CategoryList(entityCategories), baseURL);
	}

	protected String marshal(Object root, String baseURL) {
		try {
			if (LOGGER.isInfoEnabled()) {
				LOGGER.info("Base url -> {}", baseURL);
			}
			BASE_URL.set(baseURL);
			return xStream().toXML(root);
		} catch (XStreamException e) {
			throw new MarshalException(e);
		} finally {
			BASE_URL.remove();
		}
	}

}
